/*
 * Copyright (c) 2021. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package cn.edu.ntu.yyl.service.imlp;


import cn.edu.ntu.yyl.dao.RoleDao;
import cn.edu.ntu.yyl.pojo.user.Role;
import cn.edu.ntu.yyl.pojo.user.UserInfo;
import cn.edu.ntu.yyl.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleDao Dao;
    // 增
    public Integer InsertNewRole(Role role) {
        try {
            //执行SQL
            role.setId(getmaxid());
            Dao.InsertNewRole(role);
        } catch (Exception e) {
            return -1;
        }
        return 1;
    }
    // 删
    public Integer DeleteRole(Role role) {
        try {
            //执行SQL
            role.setId(getmaxid());
            Dao.DeleteRole(role);

        } catch (Exception e) {
            return -1;
        }
        return 1;
    }
    // 改
    public Integer UpdateRole(Role role) {
        try {
            //执行SQL
            role.setId(getmaxid());
            Dao.UpdateRole(role);

        } catch (Exception e) {
            return -1;
        }
        return 1;
    }
    // 查
    public List<Role> SelectAllRole() {
        try {
            //执行SQL
            return Dao.SelectAllRole();
        } catch (Exception e) {
            return null;
        }
    }

    //按照用户查询权限
    public Role SelectByUser(UserInfo userInfo) {
        try {
            //执行SQL
            return Dao.SelectByUser(userInfo);
        } catch (Exception e) {
            return null;
        }
    }
    //获取最大ID
    private Integer getmaxid() {
        //初始化
        List<Role> roles = null;
        Integer id = -1;
        try {
            //获取列表
            roles = Dao.SelectAllRole();
        } catch (Exception e) {
            System.err.println(e.toString());
        }
        //获取最大ID然后+1便是需要写入的ID
        if (roles != null) {
            for (Role role : roles) {
                if (id < role.getId()) {
                    id = role.getId();
                }
            }
        } else return -1;
        id++;
        return id;
    }
}
